package com.th.cash.th2.main

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.lxj.xpopup.XPopup
import com.th.basemodel.base.BaseVDBLazyLoadingFragment2
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.ext.bindData
import com.th.basemodel.ext.divider
import com.th.basemodel.ext.dp2px
import com.th.basemodel.ext.gotoActivity
import com.th.basemodel.ext.itemClick
import com.th.basemodel.ext.toast
import com.th.basemodel.ext.vertical
import com.th.cash.databinding.Fragment1Binding
import com.th.resmodel.R
import com.th.cash.storage.LocalSetting
import com.th.cash.th2.login.LoginActivity
import com.th.cash.th2.splash.PermissionDeniedPopup
import com.th.cash.util.ActivityRouter
import com.th.cash.util.Constants
import kotlinx.coroutines.launch

class HomeFragment : BaseVDBLazyLoadingFragment2<Fragment1Binding>() {

    private var mProductList =
        mutableListOf<HomeResponse.QlNBLMBombitaFwSlPhN.MRZamUjLamppostNaUomF>()

    private val mViewModel by viewModels<MainVm>()

    override fun startObserve() {
        lifecycleScope.launch {
            mViewModel.uiState.collect {
                when (it) {
                    is MainState.Idle -> {

                    }

                    is MainState.HomeData -> {
                        val hasTargetItem = it.data.QylNBLMBombitaFwSlPhN.any { item ->
                            item.wQFohwTEnormityOlsvnWX == "GLYDCGTESOEDYOG"
                        }

                        if (hasTargetItem) {
                            mBinding.clBigPage.visibility = View.VISIBLE
                            mBinding.clSmallPage.visibility = View.GONE
                            bandingBigCard(it.data.QylNBLMBombitaFwSlPhN)
                        } else {
                            mBinding.clBigPage.visibility = View.GONE
                            mBinding.clSmallPage.visibility = View.VISIBLE
                            bandingSmallCard(it.data.QylNBLMBombitaFwSlPhN)
                        }
                    }

                    is MainState.ProductApply -> {
                        ActivityRouter.next(requireContext(), it.data)
                    }


                    else -> {}
                }
            }
        }
    }

    private fun bandingBigCard(dataList: List<HomeResponse.QlNBLMBombitaFwSlPhN>) {
        val bigCardBean = dataList.find { item ->
            item.wQFohwTEnormityOlsvnWX == "GLYDCGTESOEDYOG"
        }?.MRZamUjLamppostNaUomFq?.get(0)

        bigCardBean?.run {
            val options = RequestOptions.bitmapTransform(RoundedCorners(16))
            Glide.with(requireContext())
                .load(wYgbjolRoutinierUQLXJwP)
                .apply(options)
                .into(mBinding.ivBigPageProductIcon)

            mBinding.ivBigPageProductName.text = MhuYpFcErythritolOTRMEni
            mBinding.ivBigPageProductPrice.text = SYDYfYfDoleriteEiARkai

            // Set button background color and text
            mBinding.tvBigProductSubmit.text = CIyoEPBCongenitalIHfVVGV
            mBinding.tvBigProductSubmit.background = GradientDrawable().apply {
                setColor(Color.parseColor(gzmHpAiEtchantRKVBocF))
                cornerRadius = resources.getDimension(R.dimen.dp_22)
            }

            // Set click listener for product info container
            mBinding.clBigPageProductInfo.setOnClickListener {
                if (!LocalSetting.userLogin) {
                    gotoActivity<LoginActivity>()
                    return@setOnClickListener
                }

                productApply(DqjXlePMelanosomeCNXzJfC)
            }
        }
    }

    private fun bandingSmallCard(dataList: List<HomeResponse.QlNBLMBombitaFwSlPhN>) {
        handleSmallCard(dataList.find { item ->
            item.wQFohwTEnormityOlsvnWX == "KRIFYGZEJIDNPTS"
        }?.MRZamUjLamppostNaUomFq?.get(0))

        handleReplayNotice(dataList.find { item ->
            item.wQFohwTEnormityOlsvnWX == "JHNFVMGQVJWGMHU"
        }?.MRZamUjLamppostNaUomFq?.get(0))

        handleProductList(dataList.find { item ->
            item.wQFohwTEnormityOlsvnWX == "UTADWCHDMVRVXNM"
        }?.MRZamUjLamppostNaUomFq)
    }

    private fun handleProductList(bean: List<HomeResponse.QlNBLMBombitaFwSlPhN.MRZamUjLamppostNaUomF>?) {
        mProductList.clear()
        if (bean?.isNotEmpty() == true) {
            mProductList.addAll(bean)
        }
        mBinding.smallPageProductList.adapter?.notifyDataSetChanged()
    }

    private fun handleReplayNotice(bean: HomeResponse.QlNBLMBombitaFwSlPhN.MRZamUjLamppostNaUomF?) {
        mBinding.imSmallProductReply.visibility = if (bean == null) {
            View.GONE
        } else {
            View.VISIBLE
        }

        bean?.run {
            val options = RequestOptions.bitmapTransform(RoundedCorners(16))
            Glide.with(requireContext())
                .load(MzmeHrxFibrocyteIluMTOw)
                .apply(options)
                .into(mBinding.imSmallProductReply)


            mBinding.imSmallProductReply.setOnClickListener {
                ActivityRouter.next(requireContext(), ODKSaOjEmbowHJdsBQj)
            }
        }
    }

    private fun handleSmallCard(bean: HomeResponse.QlNBLMBombitaFwSlPhN.MRZamUjLamppostNaUomF?) {
        bean?.run {
            val options = RequestOptions.bitmapTransform(RoundedCorners(16))
            Glide.with(requireContext())
                .load(wYgbjolRoutinierUQLXJwP)
                .apply(options)
                .into(mBinding.ivSmallPageProductIcon)

            mBinding.tvSmallPageProductName.text = MhuYpFcErythritolOTRMEni
            mBinding.tvSmallPageProductPrice.text = SYDYfYfDoleriteEiARkai

            // Set button background color and text
            mBinding.tvSmallProductSubmit.text = CIyoEPBCongenitalIHfVVGV
            mBinding.tvSmallProductSubmit.background = GradientDrawable().apply {
                setColor(Color.parseColor(gzmHpAiEtchantRKVBocF))
                cornerRadius = resources.getDimension(R.dimen.dp_22)
            }

            // Set click listener for product info container
            mBinding.clSmallPageProductInfo.setOnClickListener {
                productApply(DqjXlePMelanosomeCNXzJfC)
            }
        }
    }

    override fun init() {
        initProductAdapter()
        setPrivacyButton()
    }

    private fun initProductAdapter() {
        mBinding.smallPageProductList.vertical()
            .divider(
                color = ContextCompat.getColor(requireContext(), android.R.color.transparent),
                size = dp2px(16f)
            )
            .bindData(mProductList, R.layout.item_product_list) { holder, t, position ->


                val options = RequestOptions.bitmapTransform(RoundedCorners(5))
                Glide.with(holder.itemView.context)
                    .load(t.wYgbjolRoutinierUQLXJwP)
                    .apply(options)
                    .into(holder.getView(R.id.ivProductIcon))

                holder.setText(R.id.tvProductName, t.MhuYpFcErythritolOTRMEni)
                holder.setText(R.id.tvProductSubmit, t.CIyoEPBCongenitalIHfVVGV)


                try {
                    holder.getView<TextView>(R.id.tvProductSubmit).background =
                        GradientDrawable().apply {
                            setColor(Color.parseColor(t.gzmHpAiEtchantRKVBocF))
                            cornerRadius = resources.getDimension(R.dimen.dp_13)
                        }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                holder.setText(R.id.tvProduct1, t.SYDYfYfDoleriteEiARkai)
                holder.setText(R.id.tvProduct3, t.HIBXxaDRuggeriteHiejoPB)
                holder.setText(R.id.tvProduct6, t.KGYjlVZParsnipSaqOXmW)

            }
            .itemClick<HomeResponse.QlNBLMBombitaFwSlPhN.MRZamUjLamppostNaUomF> { data, _, position ->
                productApply(data[position].DqjXlePMelanosomeCNXzJfC)
            }
    }

    private fun productApply(productId: String) {
        if (ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.READ_SMS
            ) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(
                requireContext(),
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED
        ) {
            sendApplyProduct(productId)
        } else {
            showPermissionPop(productId)
        }
    }

    private fun sendApplyProduct(productId: String) {
        mViewModel.intentChannel.trySend(
            MainIntent.ApplyProduct(
                ProductApplyRequest(
                    productId,
                    "cakestand"
                )
            )
        )
    }

    private fun showPermissionPop(productId: String) {
        XPopup.Builder(requireContext())
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(PermissionPopup(requireContext()).run {

                clickListener = { agree ->
                    if (agree) {
                        requestPermission(productId)
                    } else {
                        if (LocalSetting.userAdult) {
                            sendApplyProduct(productId)
                        }
                    }
                }

                this
            })
            .show()
    }

    private fun requestPermission(productId: String) {
        XXPermissions.with(requireContext())
            // 申请单个权限
            .permission(
                Permission.READ_SMS,
                Permission.ACCESS_COARSE_LOCATION
            )
            // 申请多个权限
            //            .permission(Permission.Group.CALENDAR)
            // 设置权限请求拦截器（局部设置）
            //.interceptor(new PermissionInterceptor())
            // 设置不触发错误检测机制（局部设置）
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        if (LocalSetting.userAdult) {
                            sendApplyProduct(productId)
                        } else {
                            toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                        }
                        return
                    }
                    sendApplyProduct(productId)
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (LocalSetting.userAdult) {
                        sendApplyProduct(productId)
                        return
                    }

                    if (doNotAskAgain) {
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        showPermissionDeniedPopup(permissions)
                    } else {
                        toast("ไม่ได้รับอนุญาตอย่างถูกต้อง")
                    }
                }
            })
    }

    private fun showPermissionDeniedPopup(permissions: MutableList<String>) {
        XPopup.Builder(requireContext())
            .dismissOnBackPressed(false)
            .dismissOnTouchOutside(false)
            .asCustom(PermissionDeniedPopup(requireContext()).run {

                clickListener = { agree ->
                    if (agree) {
                        XXPermissions.startPermissionActivity(context, permissions)
                    }
                }

                this
            })
            .show()
    }

    private fun setPrivacyButton() {
        mBinding.tvPhonePrivacy.setOnClickListener {
            ActivityRouter.next(
                requireContext(),
                Constants.getPrivy()
            )
        }
    }

    override fun onLazyInitData() {
        mViewModel.intentChannel.trySend(MainIntent.GetHome)
    }

    override fun getVm(): BaseViewModel {
        return mViewModel
    }

    companion object {
        fun newInstance(): HomeFragment {
            return HomeFragment()
        }
    }

}